package com.gml.design.other.singleton;

/**
 * @ClassName : Singleton05
 * @Description : 懒汉式单例
 *  缩小synchronized的范围，但是同样会有线程安全问题
 * @Author : gml
 * @Date: 2021-04-01 14:30
 */
public class Singleton05 {

    private static Singleton05 INSTANCE;

    private Singleton05(){}

    public static Singleton05 getInstance() throws InterruptedException {
        if (null == INSTANCE){
            synchronized (Singleton05.class){
                Thread.sleep(100);
                INSTANCE = new Singleton05();
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++){
            new Thread(() -> {
                try {
                    System.out.println(Singleton05.getInstance().hashCode());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

}
